<template>
  <div>石材表面吸水率监测</div>
  <div>
    <el-button type="primary" @click.prevent="createData">创建数据</el-button>

    <el-button type="primary" @click.prevent="sendMessage">发送消息给服务端</el-button>
    <el-button type="primary" @click.prevent="closeWs">关闭链接</el-button>
  </div>
</template>

<script setup name="Watercontentofstone">
import { tryOnUnmounted } from '@vueuse/core'
import axios from 'axios'

const WS_ADDRESS = 'ws://172.16.106.63:8080/websocket/user-4'
// import Socket from "@/utils/socket";
// const socket = new Socket(WS_ADDRESS)
// onMounted(() => {
//   socket.connectWebSocket()
// })

import websocket from '@/utils/webSocket';
function WSOnMessage({ detail }) {
  console.log('数据',detail)
}
//初始化，初始化后任意页面均可监听消息
websocket.initWebSocket(WS_ADDRESS)
//添加事件监听，根据业务需求添加事件移除逻辑
window.addEventListener("WSOnMessage", WSOnMessage)

function createData() {
  let url = 'http://172.16.106.63:8080/channelData/selectChannelData/user-4'
  axios.get(url).then(res=>{
    console.log('44',res)
    proxy.$modal.msgSuccess("创建数据成功");
  })
}

// import { useWebSocket } from '@/hooks/index'
// const ws = useWebSocket(handleMessage,handleCloseFun)

// 2024.8.8写的
let isHandle = false  // 表示我们是否是手动关闭的ws
let ws = new WebSocket('ws://172.16.106.63:8080/websocket/user-4')
let timer = null
function openHandle() {
  console.log('连接成功')
}

function closeHandle() {
  console.log('连接关闭')
  if (!isHandle) { // 如果不是手动关闭的，则进行重连
    restart()
  }
  isHandle = false
}

function messageHandle(event) {
  console.log('收到消息', event.data)
}

function errorHandle() {
  console.log('连接错误')
}
ws.addEventListener('open', openHandle)
ws.addEventListener('close', closeHandle)
ws.addEventListener('message', messageHandle)
ws.addEventListener('error', errorHandle)

function  sendMessage() {
  //向服务端推送消息
  ws.send('hello')
}
function closeWs() {
  console.log('关闭连接')
  isHandle = true
  ws.close()
}


// 重连方法 
const restart = () => {
  console.log('客户端与服务端连接失败，准备开始重连啊')
  timer = setInterval(() => {
    console.log('重连中...')
    ws = new WebSocket('ws://172.16.106.63:8080/websocket/user-4')
    if(ws.readyState === 0){
      clearInterval(timer)
      timer = null
      ws.addEventListener('open', openHandle)
      ws.addEventListener('close', closeHandle)
      ws.addEventListener('message', messageHandle)
      ws.addEventListener('error', errorHandle)
    }
  }, 1000)
}

tryOnUnmounted(() => {
  closeWs()
})


</script>

<style lang='scss' scoped>


</style>